package com.IM.handler;

import com.IM.command.Command;
import com.IM.commandType.CommandType;
import com.IM.result.Result;
import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;


public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
     try {
         Command command = JSON.parseObject(textWebSocketFrame.text(), Command.class);
         switch (CommandType.match(command.getCode())) {
             case CONNECTION -> ConnectionHandler.execute(channelHandlerContext,command);
             case  CHAT -> ChatHandler.execute(channelHandlerContext,textWebSocketFrame);
             case JOIN_GROUP -> GroupChatHandler.execute(channelHandlerContext);
             default -> channelHandlerContext.channel()
                     .writeAndFlush(Result.fail("不支持的code"));
         }
     }catch (Exception e){
         channelHandlerContext.channel()
                 .writeAndFlush(Result.fail(e.getMessage()));
     }
    }
}
